package com.bsj.power.common.util;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.bsj.power.common.config.global.TokenUser;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Pattern;

/**
 * @author yinhao
 * @version 1.0
 * @description 用户信息常用方法
 * @date 2024/4/22
 */
@Slf4j
public class StpLoginUserUtil {

    private static final Pattern pattern = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).+$");

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static TokenUser getTokenUser() {
        Object user = null;
        try {
            user = StpUtil.getTokenSession().get("loginUser");
        } catch (NotLoginException e) {
            log.error("获取用户信息错误 : {}", ExceptionUtil.getStackStr(e));
            return null;
        }
        if (user == null) {
            return null;
        }
        return (TokenUser) user;
    }

    /**
     * 根据SaToken获取登录用户信息
     *
     * @param saToken
     * @return
     */
    public static TokenUser getTokenUserBySaToken(String saToken) {
        if (StringUtils.isEmpty(saToken)) {
            return null;
        }
        SaSession saSession = StpUtil.getTokenSessionByToken(saToken);
        if (saSession != null) {
            return (TokenUser) saSession.get("loginUser");
        } else {
            return null;
        }
    }

    /**
     * 检测密码强度
     *
     * @param password
     * @return
     */
    public static boolean isPasswordStrong(String password) {
        // 检查密码长度
        if (password.length() < 8) {
            return false;
        }
        if (!pattern.matcher(password).find()) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String s = "5jJfG&d@HsdfwJajhd*&";
        System.out.println(isPasswordStrong(s));
    }
}
